import { Message, StreamChunk, ToolCall, ChatCompletionRequest, UsageInfo, ConversationGroup } from '../types';
import { HistoryManager } from './history';
import { modelManager } from './models';
import { ToolManager } from '../tools';
import { ToolCallParser } from '../tools/parser';
import { StreamEventHandlers, StreamEventEmitter } from './stream-events';
import { configManager } from '../utils/config';
import { httpsRequestStream } from '../utils/proxy';
import { promptManager } from './prompt-manager';
import { HistorySaver } from '../ui/history-saver';

export class ChatManager {
  private historyManager: HistoryManager;
  private toolManager: ToolManager = new ToolManager();
  private maxToolCalls = 20;
  private currentToolCallDepth = 0;
  private eventEmitter: StreamEventEmitter;
  private currentUsage: UsageInfo | null = null;  // 新增：存储当前轮次的usage
  private historySaver: HistorySaver;  // 新增：历史保存器
  private currentAbortController: AbortController | null = null;  // 新增：用于取消HTTP请求

  static principleSystemPrompt: string = "";


  constructor(streamHandlers: StreamEventHandlers, historySaver?: HistorySaver) {
    this.historyManager = new HistoryManager(this.getSystemPrompt());
    this.eventEmitter = new StreamEventEmitter(streamHandlers);
    this.currentUsage = null; // 初始化currentUsage
    this.historySaver = historySaver || new HistorySaver(); // 初始化历史保存器
    ChatManager.principleSystemPrompt = promptManager.getCurrentPromptContent();

    // 新增：设置HistoryManager的自动保存回调
    this.historyManager.setAutoSaveCallback(() => {
      this.autoSaveHistory();
    });

    // 关键：设置相互引用，支持MCP工具动态更新系统提示词
    this.toolManager.setChatManagerRef(this);
  }

  // 切换提示词
  changePrinciple(index: number) {
    if (promptManager.switchPrompt(index)) {
      ChatManager.principleSystemPrompt = promptManager.getCurrentPromptContent();
      this.historyManager.updateSystemPrompt(this.getSystemPrompt());
    }
  }

  // 根据标题切换提示词
  changePromptByTitle(title: string) {
    if (promptManager.switchPromptByTitle(title)) {
      ChatManager.principleSystemPrompt = promptManager.getCurrentPromptContent();
      this.historyManager.updateSystemPrompt(this.getSystemPrompt());
    }
  }

  getSystemPrompt(): string {
    return ChatManager.principleSystemPrompt + this.toolManager.generateToolPrompt();
  }

  // 设置或更新事件处理器
  setStreamHandlers(handlers: StreamEventHandlers) {
    this.eventEmitter.setHandlers(handlers);
  }

  updateStreamHandlers(handlers: Partial<StreamEventHandlers>) {
    this.eventEmitter.updateHandlers(handlers);
  }

  // 获取事件发射器（用于外部直接监听）
  getEventEmitter(): StreamEventEmitter {
    return this.eventEmitter;
  }

  async sendMessage(userInput?: string): Promise<void> {
    let assistantMessage: string[] = [];
    let fullReasoning: string[] = [];
    try {
      // 只有用户输入时才添加用户消息和重置深度
      if (userInput) {
        this.historyManager.addUserMessage(userInput);
        this.currentToolCallDepth = 0; // 重置工具调用深度
        this.currentUsage = null; // 重置usage，避免记录上一轮的usage
        this.eventEmitter.emitDebug('开始新对话，重置工具调用深度');

      } else {
        this.eventEmitter.emitDebug('继续对话', { currentDepth: this.currentToolCallDepth });

      }

      // 检查工具调用深度限制
      if (this.currentToolCallDepth >= this.maxToolCalls) {
        return;
      }
      const currentModel = modelManager.getCurrentModel();
      const messages = this.historyManager.getMessages();

      // 过滤reasoning字段，创建用于API请求的消息副本
      const apiMessages = messages.map(msg => {
        const { reasoning, ...apiMessage } = msg;
        return apiMessage;
      });

      this.eventEmitter.emitDebug('Sending API request', {
        model: currentModel.name,
        messageCount: apiMessages.length,
        depth: this.currentToolCallDepth,
        filteredReasoning: messages.some(msg => msg.reasoning) // 记录是否过滤了reasoning
      });

      const requestBody: ChatCompletionRequest = {
        model: currentModel.name,
        messages: apiMessages, // 使用过滤后的消息
        stream: true,
        temperature: configManager.get('temperature'),
        max_tokens: configManager.get('maxTokens'),
        usage: { include: true }  // 新增：启用usage跟踪
      };


      requestBody.provider = {
        order: ["chutes"],
      }
      this.currentAbortController = new AbortController();
      // // 使用httpsRequestStream获取真正的流式响应
      const stream = httpsRequestStream("https://openrouter.ai/api/v1/chat/completions", {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${currentModel.apiKey}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify(requestBody),
        signal: this.currentAbortController.signal  // 传递取消信号
      });

      await this.processStreamResponse(stream, assistantMessage, fullReasoning);

    } catch (error) {
      const err = error instanceof Error ? error : new Error('Unknown error');

      // 标准错误处理
      this.eventEmitter.emitError(err);
      if (this.currentAbortController == null)
        assistantMessage.push("用户已终止当前消息");


    }
    // 发射流完成事件

    this.handleCompleteAssistantMessage(assistantMessage.join(""), fullReasoning.join(""));
    this.eventEmitter.emitStreamComplete();
  }

  private async processStreamResponse(body: ReadableStream<Uint8Array>, assistantMessage: string[], fullReasoning: string[]) {

    const reader = body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    let previousHadReasoning = false; // 上一个chunk是否有推理内容

    const round = this.currentToolCallDepth + 1;

    // 发射流开始事件
    this.eventEmitter.emitStreamStart(round);

    // 等待完整的流式输出
    while (true) {
      const { done, value } = await reader.read();

      // 统一处理：流结束
      if (done) {
        // 处理最后的buffer
        if (buffer.trim()) {
          const result = this.processChunk(buffer);
          previousHadReasoning = this.handleChunkResult(result, previousHadReasoning);

          if (result.usage) {
            this.currentUsage = result.usage;
            this.eventEmitter.emitDebug('收到Usage信息（最后buffer）', result.usage);
          }

          if (result.content) {
            assistantMessage.push(result.content);
          }

          if (result.reasoning) {
            fullReasoning.push(result.reasoning);
          }
        }

        // 如果流结束时还在推理状态，发射推理结束事件
        if (previousHadReasoning) {
          this.eventEmitter.emitReasoningEnd();
        }

        break;
      }

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (line.trim() === '' || line.trim() === 'data: [DONE]') continue;

        const result = this.processChunk(line);
        previousHadReasoning = this.handleChunkResult(result, previousHadReasoning);

        if (result.usage) {
          this.currentUsage = result.usage;
          this.eventEmitter.emitDebug('收到Usage信息', result.usage);
        }

        if (result.content) {
          assistantMessage.push(result.content);
        }

        if (result.reasoning) {
          fullReasoning.push(result.reasoning);
        }
      }
    }




  }

  // 处理单个chunk结果的简化逻辑
  private handleChunkResult(result: { content?: string, reasoning?: string }, previousHadReasoning: boolean): boolean {
    if (result.reasoning) {
      // 当前chunk有推理内容
      this.eventEmitter.emitReasoning(result.reasoning);
      return true; // 返回true表示当前是推理状态

    } else if (result.content) {
      // 当前chunk有内容
      if (previousHadReasoning) {
        // 上一个chunk有推理，当前有内容 = 推理阶段结束
        this.eventEmitter.emitReasoningEnd();
      }
      this.eventEmitter.emitContent(result.content);
      return false; // 返回false表示当前是内容状态
    }

    // 空chunk，保持之前的状态
    return previousHadReasoning;
  }

  private async handleCompleteAssistantMessage(fullMessage: string, fullReasoning?: string): Promise<void> {
    this.eventEmitter.emitDebug('处理完整助手消息', {
      length: fullMessage.length,
      preview: fullMessage.substring(0, 200),
      hasReasoning: !!fullReasoning,
      reasoningLength: fullReasoning?.length || 0
    });

    // 解析工具调用
    const parseResult = ToolCallParser.parseResponse(fullMessage);


    // 处理解析错误
    if (parseResult.parseError) {
      // 添加助手消息到历史（包含reasoning）
      this.historyManager.addAssistantMessage(fullMessage, undefined, this.currentUsage || undefined, fullReasoning);
      this.currentUsage = null; // 重置usage

      // 添加解析错误信息到历史
      this.historyManager.addMessage({
        role: 'user',
        content: `工具调用格式错误: ${parseResult.parseError}`
      });

      // 增加工具调用深度
      this.currentToolCallDepth++;


      // 发射工具执行错误事件
      this.eventEmitter.emitToolExecutionError('parser', parseResult.parseError);

      // 自动发送，让AI重新尝试
      try {
        await this.sendMessage(); // 递归调用，不传userInput
      } catch (error) {
        this.eventEmitter.emitError(error instanceof Error ? error : new Error('解析错误后递归调用失败'));
        this.currentToolCallDepth = 0;
        throw error;
      }
      return;
    }
  // 没有工具调用时，将usage和reasoning传递给历史管理器
    if (!parseResult.hasToolCall || !parseResult.toolCall) {    
      this.historyManager.addAssistantMessage(fullMessage, undefined, this.currentUsage || undefined, fullReasoning);
      this.currentUsage = null; // 重置usage
      this.eventEmitter.emitConversationComplete();
      return;
    }

    // 发射工具调用检测事件
    this.eventEmitter.emitToolCallsDetected([parseResult.toolCall]);

    // 步骤1: 添加助手消息（有工具调用时也要记录usage和reasoning）
    this.historyManager.addAssistantMessage(fullMessage, undefined, this.currentUsage || undefined, fullReasoning);
    this.currentUsage = null; // 重置usage

    // 步骤2: 执行工具调用并添加结果到历史
    try {
      const toolCall = parseResult.toolCall;
      const args = toolCall.function.arguments; // 直接使用对象，不再需要JSON.parse

      // 发射工具执行开始事件
      this.eventEmitter.emitToolExecutionStart(toolCall.function.name, args);

      const result = await this.toolManager.executeTool(toolCall.function.name, args);

      // 添加工具结果到历史
      this.historyManager.addToolMessage(toolCall.id, result);

      // 发射工具执行完成事件
      this.eventEmitter.emitToolExecutionComplete(toolCall.function.name, result);

      this.eventEmitter.emitDebug('工具执行成功', { toolName: toolCall.function.name });
    } catch (error) {
      const errorMsg = `工具调用失败: ${error instanceof Error ? error.message : '未知错误'}`;
      this.historyManager.addToolMessage(parseResult.toolCall.id, errorMsg);

      // 发射工具执行错误事件
      this.eventEmitter.emitToolExecutionError(parseResult.toolCall.function.name, errorMsg);

      this.eventEmitter.emitDebug('工具执行失败', { error: errorMsg });
    }

    // 步骤3: 增加工具调用深度
    this.currentToolCallDepth++;

    // 步骤4: 递归调用sendMessage继续对话
    try {
      await this.sendMessage(); // 递归调用，不传userInput

    } catch (error) {

      this.eventEmitter.emitError(error instanceof Error ? error : new Error('递归调用失败'));
      // 重置深度避免卡住
      this.currentToolCallDepth = 0;
      throw error;
    }
  }

  private lastChunk: any;
  private processChunk(line: string): { content?: string; reasoning?: string; usage?: UsageInfo } {
    try {
      // 过滤掉明显无效的行
      if (!line.trim() || line.trim() === 'data: [DONE]') {
        return {};
      }

      const jsonStr = line.replace(/^data: /, '').trim();

      // 跳过非JSON格式的数据（如错误信息等）
      if (!jsonStr.startsWith('{')) {
        return {};
      }

      const chunk: StreamChunk = JSON.parse(jsonStr);
      this.lastChunk = chunk;

      // 处理usage信息（可能在没有delta的情况下也会出现）
      let usageInfo: UsageInfo | undefined = undefined;
      if (chunk.usage) {
        // 确保所有必需字段都存在，如果API不返回则设为0
        usageInfo = {
          prompt_tokens: chunk.usage.prompt_tokens || 0,
          completion_tokens: chunk.usage.completion_tokens || 0,
          total_tokens: chunk.usage.total_tokens || 0,
          cost: chunk.usage.cost,
          reasoning_tokens: chunk.usage.reasoning_tokens,
          cached_tokens: chunk.usage.cached_tokens
        };
      }

      const delta = chunk.choices?.[0]?.delta;
      if (!delta && !usageInfo) return {};

      // 只有内容长度大于0时才处理content
      const hasValidContent = delta?.content && delta.content.length > 0;
      const hasValidReasoning = delta?.reasoning && delta.reasoning.length > 0;

      return {
        content: hasValidContent ? delta.content : undefined,
        reasoning: hasValidReasoning ? delta.reasoning : undefined,
        usage: usageInfo
      };
    } catch (e) {
      // 标准错误处理：记录解析错误
      const error = e instanceof Error ? e : new Error('Unknown parsing error');
      console.warn('⚠️ 流数据解析错误:', error.message, 'Line:', line);
      return {};
    }
  }

  // 工具管理方法
  getToolManager(): ToolManager {
    return this.toolManager;
  }
  getAvailableTools() {
    return this.toolManager.getAllTools();
  }

  addTool(tool: any) {
    this.toolManager.registerTool(tool);
    this.historyManager.updateSystemPrompt(this.getSystemPrompt());
  }

  // 新增：专门用于MCP远程工具变化时更新系统提示词
  updateSystemPromptForMCP() {
    this.historyManager.updateSystemPrompt(this.getSystemPrompt());
  }

  removeTool(toolName: string): boolean {
    const success = this.toolManager.unregisterTool(toolName);
    if (success) {
      this.historyManager.updateSystemPrompt(this.getSystemPrompt());
    }
    return success;
  }


  // MCP服务器连接管理（唯一公共接口）
  async connectMCPServer(serverName: string, command: string, cwd?: string): Promise<boolean> {
    return await this.toolManager._connectMCPServer(serverName, command, cwd);
  }

  async disconnectMCPServer(serverName: string): Promise<void> {
    await this.toolManager._disconnectMCPServer(serverName);
  }

  getHistoryManager(): HistoryManager {
    return this.historyManager;
  }

  clearHistory() {
    this.historyManager.clear();
    this.currentToolCallDepth = 0; // 重置工具调用深度
    this.currentUsage = null; // 重置usage
  }

  undoLastConversation(): boolean {
    const success = this.historyManager.removeLastConversation();
    if (success) {
      this.currentToolCallDepth = 0; // 重置工具调用深度
      this.currentUsage = null; // 重置usage
    }
    return success;
  }

  // 设置工具调用限制
  setMaxToolCalls(max: number) {
    this.maxToolCalls = Math.max(1, Math.min(50, max)); // 限制在1-50之间
  }

  getMaxToolCalls(): number {
    return this.maxToolCalls;
  }

  getCurrentToolCallDepth(): number {
    return this.currentToolCallDepth;
  }

  // 新增：获取usage相关方法
  getTotalUsage() {
    return this.historyManager.getTotalUsage();
  }

  getLastUsage(): UsageInfo | undefined {
    return this.historyManager.getLastUsage();
  }

  getUsageHistory(): UsageInfo[] {
    return this.historyManager.getUsageHistory();
  }

  // 新增：提示词管理相关方法
  getPromptManager() {
    return promptManager;
  }

  getCurrentPrompt() {
    return promptManager.getCurrentPrompt();
  }

  getAllPrompts() {
    return promptManager.getAllPrompts();
  }

  listPrompts(): string {
    return promptManager.listPrompts();
  }

  reloadPrompts() {
    promptManager.reload();
    ChatManager.principleSystemPrompt = promptManager.getCurrentPromptContent();
    this.historyManager.updateSystemPrompt(this.getSystemPrompt());
  }

  // 获取历史消息列表
  public getHistoryList(): {
    messages: Message[];
    conversations: ConversationGroup[];
    totalUsage: any;
    usageHistory: UsageInfo[];
    conversationCount: number;
  } {
    const messages = this.historyManager.getMessages();
    const totalUsage = this.historyManager.getTotalUsage();
    const usageHistory = this.historyManager.getUsageHistory();
    const conversationCount = this.historyManager.getConversationCount();

    // 按对话分组
    const conversations = this.groupMessagesByConversation(messages);

    return {
      messages,
      conversations,
      totalUsage,
      usageHistory,
      conversationCount
    };
  }

  // 将消息按对话分组的辅助方法
  private groupMessagesByConversation(messages: Message[]): ConversationGroup[] {
    const conversations: ConversationGroup[] = [];
    let currentConversation: ConversationGroup | null = null;

    for (const message of messages) {
      if (message.role === 'system') {
        continue; // 跳过系统消息
      }

      if (message.role === 'user') {
        // 开始新的对话
        if (currentConversation) {
          conversations.push(currentConversation);
        }
        currentConversation = {
          userMessage: message,
          assistantMessages: [],
          toolMessages: [],
          totalUsage: null
        };
      } else if (currentConversation) {
        if (message.role === 'assistant') {
          currentConversation.assistantMessages.push(message);
          // 累积usage信息
          if (message.usage) {
            if (!currentConversation.totalUsage) {
              currentConversation.totalUsage = { ...message.usage };
            } else {
              currentConversation.totalUsage.prompt_tokens += message.usage.prompt_tokens;
              currentConversation.totalUsage.completion_tokens += message.usage.completion_tokens;
              currentConversation.totalUsage.total_tokens += message.usage.total_tokens;
              currentConversation.totalUsage.cost = (currentConversation.totalUsage.cost || 0) + (message.usage.cost || 0);
              currentConversation.totalUsage.reasoning_tokens = (currentConversation.totalUsage.reasoning_tokens || 0) + (message.usage.reasoning_tokens || 0);
              currentConversation.totalUsage.cached_tokens = (currentConversation.totalUsage.cached_tokens || 0) + (message.usage.cached_tokens || 0);
            }
          }
        } else if (message.role === 'tool') {
          currentConversation.toolMessages.push(message);
        }
      }
    }

    // 添加最后一个对话
    if (currentConversation) {
      conversations.push(currentConversation);
    }

    return conversations;
  }

  // 从历史文件加载会话到当前聊天
  loadSessionFromHistory(messages: Message[]): void {
    // 清空当前历史，但保留系统提示词
    this.clearHistory();

    // 将历史消息加载到当前会话
    messages.forEach(message => {
      if (message.role !== 'system') { // 跳过系统消息，使用当前的系统提示词
        this.historyManager.addMessage(message);
      }
    });

    // 重置工具调用深度和usage
    this.currentToolCallDepth = 0;
    this.currentUsage = null;

    console.log(`📥 已加载历史会话: ${messages.length} 条消息`);
  }

  // 自动保存历史记录
  private autoSaveHistory(): void {
    try {
      const messages = this.historyManager.getMessages(); // 获取时间顺序的消息
      this.historySaver.saveHistory(messages);
      console.log('💾 历史记录已自动保存');
    } catch (error) {
      console.error('❌ 自动保存历史记录失败:', error);
    }

  }

  // 新增：取消当前请求
  cancelCurrentRequest(): void {
    if (this.currentAbortController) {
      this.currentAbortController.abort();
      this.currentAbortController = null;
      this.eventEmitter.emitDebug('HTTP请求已取消');
    }
  }

  // 新增：公共的abort方法
  abort(): void {
    this.cancelCurrentRequest();
    // 重置相关状态
    this.currentToolCallDepth = 0;
    this.eventEmitter.emitDebug('对话已中止，状态已重置');
  }
}